
#include "main.h"
#include <GL/gl.h>
#include <math.h>

float cam_x = 0, cam_y = 0, cam_z = 0;
float cam_pit = 0, cam_yaw = 0;

void camera_transform()
{
	glLoadIdentity();
	glRotatef(cam_pit, -1, 0, 0);
	glRotatef(cam_yaw, 0, 1, 0);
	glTranslatef(-cam_x, -cam_y, -cam_z);
}

void camera_unrotate()
{
	glRotatef(cam_yaw, 0, -1, 0);
	glRotatef(cam_pit, 1, 0, 0);
/*
	float mat[16];
	glGetFloatv(GL_MODELVIEW_MATRIX, mat);
	mat[1] = mat[2] = 0;
	mat[4] = mat[6] = 0;
	mat[8] = mat[9] = 0;
	glLoadMatrixf(mat);
*/
}

int l_Camera_SetPosition(lua_State* L)
{
	cam_x = luaL_checknumber(L, 1);
	cam_y = luaL_checknumber(L, 2);
	cam_z = luaL_checknumber(L, 3);
	return 0;
}

int l_Camera_Move(lua_State* L)
{
	cam_x += luaL_checknumber(L, 1);
	cam_y += luaL_checknumber(L, 2);
	cam_z += luaL_checknumber(L, 3);
	return 0;
}

int l_Camera_MoveRelative(lua_State* L)
{
	float forward = luaL_checknumber(L, 1);
	float right = luaL_checknumber(L, 2);
	float yaw = cam_yaw / 180 * M_PI;
	float pit = -cam_pit / 180 * M_PI;

	cam_x += right * cos(yaw) + forward * sin(yaw) * cos(pit);
	cam_y -= forward * sin(pit);
	cam_z += right * sin(yaw) - forward * cos(yaw) * cos(pit);
	return 0;
}

void cap()
{
	while (cam_yaw >  180.) cam_yaw -= 360.;
	while (cam_yaw < -180.) cam_yaw += 360.;
	if (cam_pit >  90) cam_pit =  90.;
	if (cam_pit < -90) cam_pit = -90.;
}

int l_Camera_SetRotation(lua_State* L)
{
	cam_yaw = luaL_checknumber(L, 1);
	cam_pit = luaL_checknumber(L, 2);
	cap();
	return 0;
}

int l_Camera_Rotate(lua_State* L)
{
	cam_yaw += luaL_checknumber(L, 1);
	cam_pit += luaL_checknumber(L, 2);
	cap();
	return 0;
}

int l_Camera_GetRotation(lua_State* L)
{
	lua_pushnumber(L, cam_yaw);
	lua_pushnumber(L, cam_pit);
	return 2;
}
